<?php
	include ('../defines.php');
	FunctionsHelper::includeFiles(
		array(
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'users.php',
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'tournaments.php',
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'players.php',
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'countries.php',
			ADMINISTRATOR_CONTROLLER_DIRECTORY . 'matches.php'
		)
	);
	
	
	$users = new Users();
	$tournaments = new Tournaments();
	$players = new Players();
	$countries = new Countries();
	if (!$users->isLoggedUser())
		header('Location:' . ADMINISTRATOR_VIEW_PATH . 'login.php');
	
	$user = $users->getLoggedUser();
	if (!empty($_POST)){
		$matches = new Matches();

		$tournament = $_POST['tournament_id'];
		unset($_POST['sbmSubmit']);

		$inserted = $matches->insertMatches($_POST);
		if ($inserted)
			header('Location:' . ADMINISTRATOR_VIEW_PATH . 'matches_am.php?tournament=' . $tournament);
	}

	$tournament = $tournaments->getTournament(
		array(
			'tournament_id' => $_GET['tournament']
		)
	);

	$arrMatches = $tournaments->getAllMatches(
		array(
			'class' => $tournament->getClass()->getDescription(),
			'tournament_id' => $_GET['tournament']
		)
	);

	$tournament->setHasMatches(count($arrMatches));
	$tournament->setMatches($arrMatches);
	$arrRounds = $tournaments->getRounds();
	$countRounds = count($arrRounds);

	$arrCountMatches = array ();
	for ($i=0;$i<$countRounds;$i++)
		$arrCountMatches[$i] = 0;
		
	foreach($arrMatches as $oneMatch){
		$arrCountMatches[$oneMatch->Round->getRoundId() - 1]++;
	}

	$arrPlayers = $players->getAllOfSex($_REQUEST['sex']);
	$arrCountries = $countries->getAll();
	$normalTournament = strtolower($tournament->getClass()->getDescription()) != 'nations' ? 1 : 0;
	FunctionsHelper::includeTop();
?>
<div class="withBorder" id="main">
	<script type="text/javascript">
		var counter = [];
		var style = <?= $tournament->getClass()->getClassId();?>;
		var initialResultValue = 'Resultado';
		var initialPlaceValue = 'Lugar | Superficie';
		var normalTournament = <?= $normalTournament;?>;
		var sex = "<?=$_REQUEST['sex'];?>";
		$(function(){
			if (normalTournament){
				var comboToChoose = $('#sltPlayers');
				var deleteOperation = 'deleteMatch';
			}else{
				var comboToChoose = $('#sltCountries');
				var deleteOperation = 'deleteInternationalMatch';
			}

			<?php
			for ($i = 0; $i < $countRounds; $i++){
			?>
				counter[<?= $i;?>] = <?= $arrRounds[$i]['total_matches'] - $arrCountMatches[$i]?>;
			<?
			}
			?>
			$('#back').click(function(){
				document.location.href='<?=ADMINISTRATOR_VIEW_PATH;?>tournaments.php';
			});
			$('.deleteMatch').click(function(){
				varUrl = '<?=ADMINISTRATOR_CONTROLLER_PATH; ?>operations.php';
				varData = { 'id' : this.id, 'controller' : 'tournaments', 'operation' : deleteOperation };
				callAjax(varUrl, 'post', varData, funcDeleteRow($(this).find('img')));
				var round = $(this).data('round');
				counter[round-1] = counter[round-1] + 1;
			});
			$('a.addMatch').live('click', function(){
				var round = $(this).data('id');
				if (counter[round-1]>0){
					combos = createCombos(comboToChoose, round);
					insertIntoHTML($(this), combos);			
					counter[round-1] = counter[round-1] - 1;
				}else{
					alert('No se puede ingresar mas partidos, para ingresar debe eliminar alguno de los creados.');
				}
			});
			
			$('.deleteRow').live('click', function(){ 
				var newMatchDiv = $(this).parent().parent();
				var round = newMatchDiv.find('a.addMatch').data('id');
				counter[round-1] = counter[round-1] + 1;
				$(this).parent().remove();
			});
			
			$('.result').live('focus', function(){
				if ($(this).val() == initialResultValue)
					$(this).val('');
				changeClass($(this));
			});

			$('.place').live('focus', function(){
				if ($(this).val() == initialPlaceValue)
					$(this).val('');
				changeClass($(this));
			});

			$('.see').live('mouseout', function(){
				closePopup($('.popup'));
			});
			
			$('.see').live('mouseover', function(){
				matchDescription = $(this).data('match');
				position = $(this).position();
				id = $(this).attr('id');
				
				PopupSettings = {
					Top: position.top - 50,
					Left: position.Left - 200
				};
				currentPlacePopupFunction = function(){ if (PopupSettings != undefined){ $('.popup').css('top', PopupSettings.Top + 'px'); $('.popup').css('left', PopupSettings.Left + 'px'); } }
				fillMatchesInPopup(matchDescription, id, true);
			});
			
			$('.addPlayerMatches').live('click', function(){
				idSerie = $(this).data('id');
				matchDescription = $(this).data('match');
				
				setUpPopupContext(this);
				createPlayerCombos(idSerie, matchDescription);
				$('.popup .to-modify').removeClass('hidden');
			});
		
			$('.round-section .edit').live('click', function(){ 
				var round = $(this).data('id');
				combos = createCombos(comboToChoose, round);
				insertCombos(combos, $(this));
			});
			
		});

		var insertCombos = function(combos, $editCaller){
			count = 0;
			name = combos[0].attr('name');
			divname = name.split('[]');
			
			if ($editCaller != undefined){
				$currentMatch = $editCaller.closest('.currentMatch');
				id = $currentMatch.find('.id').val() != undefined ? $currentMatch.find('.id').val() : 0;
				round_id = $currentMatch.find('.round-id').val();
				$currentMatch.find('*').remove();
				$currentMatch.append(combos[0].attr('name', 'mod_' + round_id + '_' + id + '[]'))
					.append('<span class="nonUnderlined"> vs. </span>')
					.append(combos[1].attr('name', 'mod_' + round_id + '_' + id + '[]'))
					.append('<input type="text" name="mod_' + round_id + '_' + id + '[]" id=" + place_mod_' + round_id + '_' + id + '" value="' + initialResultValue + '" class="result initialResultStyle" />')
					.append('<input type="text" name="place_mod_' + round_id + '_' + id + '[]" id="place_mod_' + round_id + '_' + id + '" value="' + initialPlaceValue + '" class="place initialResultStyle" />');
			}
		}
		
		
		var insertIntoHTML = function(currentLink, combos){
			count = 0;
			name = combos[0].attr('name');
			
			divname = name.split('[]');
			$(currentLink).before('<div class="div' + divname[0] + '"></div>');
			$.each(combos, function(){
				$('.div' + divname[0]).append($(this));
				if (count == 0)
					$('.div' + divname[0]).append('<span class="nonUnderlined"> vs. </span>');
				count++;
			});
			$('.div' + divname[0]).append('<input type="text" name="' + name + '" id="' + name + '" value="' + initialResultValue + '" class="result initialResultStyle" />');
			if (!normalTournament)
				$('.div' + divname[0]).append('<input type="text" name="place_' + name + '" id="place_' + name + '" value="' + initialPlaceValue + '" class="place initialResultStyle" />');
			$('.div' + divname[0]).append('<a href="#" class="deleteRow">Eliminar</a>');
			$('.div' + divname[0]).append('<br />');
		};

		var fillMatchesInPopup = function(match, id, toSee){	
			$.ajax({
				url:  '<?=ADMINISTRATOR_CONTROLLER_PATH; ?>operations.php',
				data: { 'id' : id, 'controller' : 'matches', 'operation' : 'getAllFromSerie' },
				type: 'post',
				success: function(data){
					data = $.parseJSON(data);
					HTML = '';
					addMatchesList(data);
					openPopup(toSee);
				}
			});
		};

		var PopupSettings = {
			Left: 0,
			Top: 0
		};
		
		var defaultPlacePopupFunction = function(){
//			$('.popup').css('top', screen.height/2 + 'px').css('left', screen.width/2 + 'px');
			$('.popup').removeAttr('css');
		};
		
		var currentPlacePopupFunction = function(){};
		
		var createPlayerCombos = function(idSerie, matchDescription){
			callAjax(
				'<?=ADMINISTRATOR_CONTROLLER_PATH; ?>operations.php', 
				'post', 
				{ 'id' : $('#country1').val(), 'sex' : '<?= $_REQUEST['sex']; ?>', 'controller' : 'players', 'operation' : 'getFromNationAndSex' }, 
				function(data){
					data = $.parseJSON(data);
					if (data.length > 0){
						HTML = '<select class="comboPlayers" id="local">';
						$.each(data, function(){
							HTML += '<option value="' + this.player_id + '">' + this.name + ' ' + this.surname + '</option>';
						});
						HTML += '</select>';

						callAjax(
							'<?=ADMINISTRATOR_CONTROLLER_PATH; ?>operations.php',
							'post', 
							{ 'id' : $('#country2').val(), 'sex' : '<?= $_REQUEST['sex']; ?>', 'controller' : 'players', 'operation' : 'getFromNationAndSex' },
							function(data){
								data = $.parseJSON(data);
								if (data.length > 0){
									HTML2 = '<select class="comboPlayers" id="visitor">';
									$.each(data, function(){
										HTML2 += '<option value="' + this.player_id + '">' + this.name + ' ' + this.surname + '</option>';
									});
									HTML2 += '</select>';

									HTMLF = HTML + HTML2;
									$('.popup .combo').append(HTMLF);
									$('.comboPlayers').hide();
									replicatePlayersCombo();
									
									fillMatchesInPopup(matchDescription, idSerie);
								}else{
									alert('No puede cargarle partidos a la serie debido a que una de las dos naciones no tiene jugadores.');
									return false;
								}
							}
						);
					}else{
						alert('No puede cargarle partidos a la serie debido a que una de las dos naciones no tiene jugadores.');
						return false;
					}
				}
			);	
		};

		var setUpPopupContext = function(element){
			match = $(element).data('match');
			country1Id = $(element).data('country1');
			country2Id = $(element).data('country2');
			serieId = $(element).data('id');
			tournament_id = $('#tournament_id').val();
			$('#matchesTitle > span').html(match);
			$('#country1').val(country1Id);
			$('#country2').val(country2Id);
			$('#serie_id').val(serieId);
			$('#tournament_id_popup').val(tournament_id);
			
			currentPlacePopupFunction = defaultPlacePopupFunction;
		};
		
		var closePopup = function($popup){
			popupId = $popup.attr('id');
			$.each($('#' + popupId + ' input[type=text]'), function(){
				$(this).val('');
			});
			$('.popup .comboPlayers').remove();
			$('.popup .popupContent').html('').css('height', '43px');
			$popup.addClass('hidden');
		};
		
		var openPopup = function(toSee){
			currentPlacePopupFunction();
			$('.popup').removeClass('hidden');
			
			if (toSee)
				$('.popup .to-modify').addClass('hidden');
		};
		
		var changeClass = function(element){
			if (element.hasClass('initialResultStyle')){
				element.addClass('finalResultStyle');
				element.removeClass('initialResultStyle');
			}
		};
		
		var createCombos = function(combo, round){
			var NC = [];

			for (a = 0; a < 2; a++){
				var oneCombo = combo.clone();
				name = 'match_' + round + '_' + counter[round-1] + '[]'; //match_ronda_jugador_id propio
				oneCombo.attr('name', name);
				oneCombo.attr('id', name);
				oneCombo.removeClass('helper');
				NC.push(oneCombo);
			}
			return NC;
		};
	</script>
	
	<div class="mainABM bigMain">
		<select id="sltPlayers" class="helper">
		<?foreach ($arrPlayers as $player){?>
			<option value="<?= $player->getPlayerId();?>"><?= $player->getName() . ' ' . $player->getSurname();?></option>
		<?}?>
		</select>
		
		<select id="sltCountries" class="helper">
		<?foreach ($arrCountries as $country){?>
			<option value="<?= $country->getCountryId();?>"><?= $country->getName();?></option>
		<?}?>
		</select>
		<div class="ABMtitle"><h1>ADMINISTRADOR DE PARTIDOS</h1></div>
		
		<? if (!$normalTournament){?>
		<p>
			Antes de insertar los partidos de la serie debe guardarla creada.
			<br />
			<br />
			Si inserta un partido dentro de una serie se eliminar&aacute;n todos los que fueron creados con anterioridad por lo que deber&aacute; ingresar todos los partidos de la serie.
		</p>
		<? }?>
		
		<form id='frmCompetition' class='form' method='POST'>
			<input type='hidden' name='tournament_id' id='tournament_id' value='<?= $_GET['tournament']; ?>' />
			<input type='hidden' name='normal_tournament' id='normal_tournament' value='<?= $normalTournament; ?>' />
			<div class="label nonModificable"><?= $tournament->getName() . ' (' . $tournament->getSex() .')';?></div>
			<br />
			<div id="currentMatches">
			<div class="label labelBigger">Partidos cargados anteriormente</div>
			<br />
			<?php
			$countMatches = count($arrMatches);
			foreach ($arrRounds as $round){
				echo '<div class="round-section">';
				echo '<div class="label labelBigger round">' . $round['description']. '</div>';
				foreach ($arrMatches as $match){

					if ($round['round_id'] == $match->Round->getRoundId()){
			?>	
						<div class="currentMatch">
							<div class="description">
								<input type="hidden" class="id" value="<?= $match->Id;?>" />
								<input type="hidden" class="round-id" value="<?= $match->Round->getRoundId();?>" />
								<?= $match->First;?> vs. <?= $match->Second;?> [ <?= $match->Result;?> ]
								<?
								if (!$normalTournament){
									$place = trim($match->Place);
									if (!empty($place)){
								?>
									- [ Jugado en: <span class="bold"><?= $place;?> </span>]
								<?
									}
									$surface = trim($match->Surface);
									if (!empty($surface)){
								?>
									- [ Superficie: <span class="bold"><?= $surface;?> </span>]
								<?	
									}
								?>
								<img class="addPlayerMatches link mini" data-country1="<?=$match->FirstId;?>" data-country2="<?=$match->SecondId;?>" data-id="<?= $match->Id;?>" data-match="<?= $match->First . ' vs. ' . $match->Second;?>" src="<?= ADMINISTRATOR_IMAGE_PATH . 'add_mini.png'; ?>" title="Agregar jugadores" alt="Agregar jugadores" />
							<? } ?>
							</div>
							<a class="deleteMatch link" href="#" id="<?= $match->Id;?>" data-round="<?= $round['round_id']?>"><img src="<?= ADMINISTRATOR_IMAGE_PATH . 'delete_mini.png'; ?>" title="Eliminar" alt="Eliminar" class="mini" /></a>
							<? if ($match->HasMatches > 0){ ?>
								<img id="<?= $match->Id;?>" data-match="<?= $match->First . ' vs. ' . $match->Second;?>" class="see link mini" src="<?= ADMINISTRATOR_IMAGE_PATH . 'glass.png'; ?>" title="Ver" alt="Ver" class="mini" />					
							<? }else{ ?>
								<img id="<?= $match->Id;?>" data-match="<?= $match->First . ' vs. ' . $match->Second;?>" data-id="<?= $match->Id;?>" class="edit link mini" src="<?= ADMINISTRATOR_IMAGE_PATH . 'edit_mini.png'; ?>" title="Editar" alt="Editar" class="mini" />					
							<? } ?>
							<br />
						</div>
			<?
						unset($match);
					}
				}
				echo '<div class="newMatch"><a class="addMatch" href="#" data-id="' . $round['round_id'] . '">Nuevo</a></div>';
			}
			echo '</div>';
			?>
			</div>
			<div id="button"><input type="submit" name='sbmSubmit' id='sbmSubmit' value='Aceptar'  /></div>
		</form>
		<img class="back" src='<?= ADMINISTRATOR_IMAGE_PATH . 'back.png'; ?>' id="back" width='64' height='52' />
	</div>
</div>

<?php
	FunctionsHelper::includeBottom(true);
?>